import ADQ from "../Core/ADQ";
import { IEventHandler } from "../Interfaces/IUtils";
import CloneTools from "../Utils/CloneTools";
import { WatcherBase } from "./WatcherBase";

/**
 * 数据监听
 */
export class Watcher extends WatcherBase {
  watchUpdateFn: IEventHandler; //数据变化侦听器
  /**
   * 监听器构造函数
   * @param ivm 监听VM
   * @param expOrFns  读取数据方法
   * @param node 监听节点
   * @param attrName 监听属性
   * @param updateCalls 更新
   */
  constructor(ivm, expOrFns, node, attrName, updateCalls) {
    super(ivm, expOrFns, node, attrName, updateCalls);
    //存储值变化监听器
    let watch = this.vm.$options.watch;
    watch &&
      watch[expOrFns] &&
      (this.watchUpdateFn = ADQ.getHandler().create(
        this.vm,
        watch[expOrFns],
        null,
        false
      ));

    /**挂载主VM订阅器  */
    this.subIds = {};

    this.isArray = Array.isArray(this.get());
    if (this.isArray) {
      this.watchAttrName.watch = this.watchUpdateFn;
    }
  }
  /**
   *绑定视图更新数据
   */
  run() {
    let oldVal = this.isArray
      ? CloneTools.deepCopy(this.value)
      : this.value;
    let newVal = this.get();

    if (newVal === oldVal) {
      return;
    } else {
      this.value = newVal;
    }
    if (this.watchUpdateFn) {
      //执行监听函数获取改变值
      if (!this.isArray) {
        var returnValue = this.watchUpdateFn.runWith([
          newVal,
          oldVal,
          this.watchNode,
        ]);
        newVal = returnValue ? returnValue : newVal;
      }
    }
    // 将newVal, oldVal挂载到MVVM实例上
    this.updateCall.call(this.vm, newVal, oldVal);
  }
}
